package com.talking.controller;

import com.talking.dao.GroupMapper;
import com.talking.dao.RecordMapper;
import com.talking.pojo.*;
import com.talking.service.*;
import com.talking.tools.MailCode;
import com.talking.tools.MybatisTools;
import com.talking.tools.ThreadPool;
import org.apache.ibatis.session.SqlSession;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

public class ReceiveThread extends Thread{
    private Socket client;
    private ObjectInputStream in;
    private ObjectOutputStream out;
    private volatile boolean isRunning;
    private Message inMSG;
    private Message outMSG;
    private UserService userService;
    private RelationService relationService;
    private GroupService groupService;

    public ReceiveThread(Socket client, ObjectInputStream in, ObjectOutputStream out){
        this.isRunning = true;
        userService = new UserService();
        relationService = new RelationService();
        groupService = new GroupService();

        this.client = client;
        this.in = in;
        this.out = out;

    }
    public ObjectOutputStream getOut(){
        return out;
    }

    public void run(){
        // 写出的值与客户端读取不一致
        //则可能是outMSG没有重新赋值
        try {
            while (isRunning) {
                System.out.println("\n消息监听");
                inMSG = (Message) in.readObject();
                System.out.println("监听到请求："+inMSG.getMessageType());

                switch (inMSG.getMessageType()){
                    //获取好友列表
                    case MessageType.GET_FRIENDS:
                        System.out.println("接收到请求：获取好友列表功能");
                        outMSG = new Message();
                        User user =(User) inMSG.getContent();
                        List<User> userList = userService.getFriendListService(user.getUser_id());

                        outMSG.setMessageType(MessageType.GET_FRIENDS);
                        outMSG.setResponseType(ResponseType.SUCCESS);
                        outMSG.setContent(userList);
                        out.writeObject(outMSG);
                        break;

                    //获取群列表
                    case MessageType.GET_GROUPS:
                        System.out.println("接收到请求：获取群列表功能");
                        outMSG = new Message();
                        User groupNumber =(User) inMSG.getContent();
                        List<Group> groupList = groupService.getUserGroup(groupNumber.getUser_id());

                        outMSG.setMessageType(MessageType.GET_GROUPS);
                        outMSG.setResponseType(ResponseType.SUCCESS);
                        outMSG.setContent(groupList);
                        out.writeObject(outMSG);
                        break;

                     //获得离线消息
                    case MessageType.GE_OFFLINE_MSG:
                        System.out.println("接收到请求：获取离线消息"+(int)inMSG.getContent());
                        RecordService recordService = new RecordService();
                        int user_id = (int)inMSG.getContent();
                        List<Record> offLineMSG = recordService.getRecordsByUserID(user_id,false);
                        recordService.updateRecord(user_id);

                        for (Record record : offLineMSG) {
                            System.out.println(record.toString());
                        }
                        outMSG = new Message();
                        outMSG.setContent(offLineMSG);
                        out.writeObject(outMSG);
                        break;

                     //获得群成员信息
                    case MessageType.GET_GROUP_NUMBERS:
                        System.out.println("接收到请求：获得群成员");
                        outMSG = new Message();
                        Group group = (Group) inMSG.getContent();
                        UserService userService1 = new UserService();
                        List<User> groupNumbers = userService1.getGroupNumbers(group.getGroup_id());
                        outMSG.setMessageType(MessageType.GET_GROUP_NUMBERS);
                        outMSG.setContent(groupNumbers);
                        outMSG.setResponseContent(String.valueOf(group.getGroup_id()));
                        out.writeObject(outMSG);
                        break;

                     //创建群
                    case MessageType.CREATE_GROUP:
                        System.out.println("接收到请求：创建群");
                        SqlSession sqlSession = MybatisTools.getSqlSession();
                        groupService.setSqlSession(sqlSession);                 //设置sqlsession，用于同一个连接
                        relationService.setSqlSession(sqlSession);
                        Group newGroup = (Group) inMSG.getContent();

                        outMSG = new Message();
                        outMSG.setMessageType(MessageType.UPDATE_GROUP_LIST);
                        if (groupService.insertNewGroup(newGroup)==1){
                            //成功插入群,记得处理事物回滚
                            int lastID = groupService.getLastID();
                            if (lastID!=0&&relationService.insertUserRelationService(newGroup.getCreator_id(),lastID,false)==1){
                                outMSG.setContent(new GroupService().getUserGroup(newGroup.getCreator_id()));
                                outMSG.setResponseType(true);
                            }else
                                outMSG.setResponseType(false);

                        }else
                            outMSG.setResponseType(false);

                        out.writeObject(outMSG);
                        break;

                    //邀请加入群聊
                    case MessageType.INVITE_NUMS:
                        System.out.println("接收到请求：邀请加入群聊");
                        outMSG = new Message();

                        outMSG.setResponseType(groupService.inviteNums((Notice)inMSG.getContent()));
                        break;

                    //退出群聊
                    case MessageType.EXIT_GROUP:
                        outMSG = new Message();
                       new GroupService().exitGroup((Notice)inMSG.getContent(),out);

                        break;

                    //聊天功能
                    case MessageType.CHAT:
                        System.out.println("接收到请求：聊天功能");
                        ChatMsg chatMsg =(ChatMsg) inMSG.getContent();
                        if (chatMsg.isSignChat())
                            userService.chatService((ChatMsg) inMSG.getContent());
                        else{
                            List<User> groupNums = userService.getGroupNumbers(((Group)chatMsg.getReceiver()).getGroup_id());
                            groupService.groupChat(chatMsg,groupNums);
                        }
                        break;

                    //注销
                    case MessageType.LOGOUT:
                         System.out.println("接收到请求：注销功能");
                         User sender =(User) inMSG.getContent();
                         outMSG = new Message();

                         ThreadPool.removeThread(sender.getUser_id());
                         outMSG.setMessageType(MessageType.LOGOUT);
                         outMSG.setResponseType(true);

                         out.writeObject(outMSG);
                         isRunning = false;
                         this.close();
                         break;

                    //退出
                    case MessageType.OFFLINE:
                        System.out.println("接收到请求：退出功能");
                        User client =(User) inMSG.getContent();
                        outMSG = new Message();

                        ThreadPool.removeThread(client.getUser_id());
                        outMSG.setMessageType(MessageType.OFFLINE);
                        outMSG.setResponseType(true);

//                        out.writeObject(outMSG);
                        isRunning = false;
                        this.close();
                        break;

                    //查找好友
                    case MessageType.SEARCH_FRI:
                        System.out.println("接收到请求：查找好友功能");
                        String id = ((User)inMSG.getContent()).getUser_mail();
                        outMSG = new Message();

                        List<User> friend = userService.getUserByOneService(id);
                        outMSG.setMessageType(MessageType.SEARCH_FRI);
                        outMSG.setContent(friend);
                        out.writeObject(outMSG);
                        break;

                    //好友添加申请
                    case MessageType.FRIEND_REQUEST:
                        System.out.println("接收到请求：好友添加申请功能");
                        userService.noticeService((Notice) inMSG.getContent());
                        break;

                    //确认添加好友
                    case MessageType.NOTICE:
                        System.out.println("接收到请求：好友添加或群添加确认！");
                        Notice notice = (Notice) inMSG.getContent();
                        NoticeService noticeService = new NoticeService(out);

                        if (notice.isUserNotice()){
                            noticeService.addFriend(notice);
                        }else {
                            noticeService.joinGroup(notice);
                        }
                        break;

                     //删除好友功能
                    case MessageType.DELETE_FRI:
                        System.out.println("接收到请求：好友删除功能");
                        Notice notice1 = (Notice) inMSG.getContent();
                        User sender1 = notice1.getSender();
                        int s = sender1.getUser_id();
                        List<User> receivers = notice1.getReceiver();
                        int r = receivers.get(0).getUser_id();
                        int t = relationService.deleteUserRelation(s,r,true);
                        if (t==1){
                            System.out.println("接收到请求：删除成功");

                            outMSG = new Message();
                            outMSG.setMessageType(MessageType.DELETE_FRI);
                            outMSG.setContent(new UserService().getFriendListService(s));
                            ThreadPool.getThread(s).getOut().writeObject(outMSG);

                            outMSG.setContent(new UserService().getFriendListService(r));
                            if (ThreadPool.getThread(r)!=null)
                                ThreadPool.getThread(r).getOut().writeObject(outMSG);
                        }
                        System.out.println("删除结果"+t);
                        break;

                    //发送邮件验证码
                    case MessageType.GET_MAIL_CODE:
                        outMSG = new Message();
                        String mail = (String) inMSG.getContent();
                        System.out.println("接收到请求：给 "+mail+" 发送邮箱验证码");

                        MailService mailService = new MailService();
                        mailService.createMailCode(mail);
                        String mailCode = mailService.getMailCode(mail);
                        MailController controller = new MailController(mail, mailCode);
                        boolean temp = controller.sendMail();

                        outMSG.setResponseType(temp);
                        outMSG.setMessageType(MessageType.GET_MAIL_CODE);
                        out.writeObject(outMSG);

                        break;

                    //修改用户资料
                    case MessageType.UPDATE_USER_MSG:
                        System.out.println("接收到请求：修改用户资料");
                        outMSG = new Message();
                        User updater = (User) inMSG.getContent();
                        String mailCode1 = (String) inMSG.getResponseContent();
                        String tempMail = updater.getUser_mail();
                        if (mailCode1!=null){
                            String tempCode = MailCode.getCode(tempMail);
                            boolean flag = tempCode.equals(mailCode1);
                            if (!flag){
                                outMSG.setMessageType(MessageType.UPDATE_USER_MSG);
                                outMSG.setResponseType(false);
                                outMSG.setResponseContent("验证码错误！");
                                out.writeObject(outMSG);
                                break;
                            }

                        }

                        int i = userService.updateUserMessService(updater);
                        System.out.println("执行结果"+i);
                        if (i==1){
                            if (updater.getUser_pwd()==null){
                                System.out.println("修改资料");

                            outMSG.setMessageType(MessageType.UPDATE_USER_MSG);
                                System.out.println(updater.toString());
                            User user2 = userService.getUserMSGByIDService(updater.getUser_id());
                                System.out.println(user2.toString());
                            outMSG.setContent(user2);
                            outMSG.setResponseType(true);
                            out.writeObject(outMSG);

                            }else {
                                System.out.println("修改密码");
                                ThreadPool.removeThread(updater.getUser_id());
                                outMSG.setMessageType(MessageType.OFFLINE);
                                outMSG.setResponseType(true);

                                out.writeObject(outMSG);
                                isRunning = false;
                                this.close();
                            }
                        }
                        break;

                    default:
                        break;

                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void close(){
        try {
            client.close();
            in.close();
            out.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
